package com.fdb.smcts.web.util;

import com.fdb.smcts.core.constant.ApplicationConstance;
import com.fdb.smcts.core.util.SpringContextUtils;
import com.fdb.smcts.core.vo.EngineHttpRequestVO;
import com.fdb.smcts.core.vo.EngineHttpResponseVO;
import com.fdb.smcts.web.http.EngineHttpClient;
import com.fdb.smcts.web.http.HttpClient;

/**
 * 
 * 调用流程引擎启动流程工具
 * 
 * @author Cytus_
 * @since 2018年5月11日 下午4:13:33
 * @version 1.0
 *
 */
public class HttpClientUtil {
	
	public static final String ENGINE_RESTFUL_HTTP_CLIENT_BEANID = "engineRestfulHttpClient";
	
	public static final String DEFAULT_RESTFUL_HTTP_CLIENT_BEANID = "defRestfulHttpClient";

	/**
	 * 调用流程引擎启动流程
	 * @param url
	 * @param requestObject
	 * @param responseClass
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public final static <T> T callFlowEngine(String url, EngineHttpRequestVO engineHttpReqVo, Class<T> responseClass) throws Exception {
		HttpClient<EngineHttpRequestVO, EngineHttpResponseVO> httpClient = SpringContextUtils.getBean(ENGINE_RESTFUL_HTTP_CLIENT_BEANID, EngineHttpClient.class);
		EngineHttpResponseVO respVO = httpClient.httpCall(url, engineHttpReqVo, EngineHttpResponseVO.class);
		if (!respVO.getResult()) {
			throw new Exception(respVO.getErrorCode() +":"+ respVO.getErrorMsg());
		}
		return (T) respVO.getData();
	}
	
	/**
	 * 异步继续当前事件
	 * @param url
	 * @param bizSerno
	 * @param eventId
	 * @param requestObject
	 * @return
	 * @throws Exception
	 */
	public final static boolean continueFlow(String url, String bizSerno, String eventId, Object requestObject) throws Exception {
		HttpClient<EngineHttpRequestVO, EngineHttpResponseVO> httpClient = SpringContextUtils.getBean(ENGINE_RESTFUL_HTTP_CLIENT_BEANID, EngineHttpClient.class);
		EngineHttpRequestVO reqVO = new EngineHttpRequestVO(bizSerno, eventId);
		reqVO.setData(requestObject);
		EngineHttpResponseVO respVO = httpClient.httpCall(url, reqVO, EngineHttpResponseVO.class);
		if (!respVO.getResult()) {
			throw new Exception(respVO.getErrorCode() +":"+ respVO.getErrorMsg());
		}
		return ApplicationConstance.SUCCESS.equals(respVO.getData());
	}
	
	/**
	 * 用默认的方式调用http
	 * @param url
	 * @param inArgs
	 * @param outClass
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public final static <O> O httpClient(String url, Object inArgs, Class<O> outClass) throws Exception {
		HttpClient<Object, O> httpClient = (HttpClient<Object, O>) SpringContextUtils.getBean(DEFAULT_RESTFUL_HTTP_CLIENT_BEANID);
		return httpClient.httpCall(url, inArgs, outClass);
	}
	
}
